package com.duanjw.springcloud.openfeign.provider.web;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.NacosServiceInstance;
import com.alibaba.cloud.nacos.NacosServiceManager;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.client.naming.NacosNamingService;
import com.duanjw.springcloud.openfeign.provider.feign.ConsumerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 提供者 controller
 *
 * @author duanjw
 */
@RestController
@RequestMapping("provider")
public class ProviderController {

    /**
     * 向注入普通 bean 一样注入服务消费者者接口
     */
    private final ConsumerClient consumerClient;

    /**
     * 获取当前服务信息
     */
    private final NacosDiscoveryProperties nacosDiscoveryProperties;

    public ProviderController(NacosDiscoveryProperties nacosDiscoveryProperties, ConsumerClient consumerClient) {
        this.nacosDiscoveryProperties = nacosDiscoveryProperties;
        this.consumerClient = consumerClient;
    }

    /**
     * echo
     * <p>
     * 访问地址：curl localhost:7008/provider/echo/OpenFeignProvider\?value2=a
     *
     * @param value
     * @return
     */
    @GetMapping("echo/{value}")
    public String hello(@PathVariable String value, @RequestParam String value2, HttpServletRequest request) {
        Enumeration<String> headerNames = request.getHeaderNames();
        System.out.println("headerNames" + headerNames);
        do {
            System.out.println("请求头中的参数：" + request.getHeader(headerNames.nextElement()));
        }while (headerNames.hasMoreElements());

        String ip = nacosDiscoveryProperties.getIp();
        int port = nacosDiscoveryProperties.getPort();
        System.out.println(value);
        System.out.println(value2);
        return String.format("Hello %s，openfeign-provider ip: %s，port： %s", value, ip, port);
    }

    /**
     * 使用 openfeign 调用其它服务
     * <p>
     * 请求地址：curl localhost:7008/provider/openfeign
     *
     * @return
     */
    @GetMapping("openfeign")
    public String openfeign() {
        String value = "Openfeign";
        return consumerClient.hello(value);
    }
}